#include <unistd.h>
#include "clnt_socks.h"
#include <pthread.h>
#include <string.h>
#include <stdio.h>

#define MAX_CLNT 256
#define NAME_SIZE 128
#define BUF_SIZE 1024
char g_cln_names[MAX_CLNT][NAME_SIZE];
int g_clnt_socks[MAX_CLNT] = {0};
int g_clnt_cnt = 0;

pthread_mutex_t g_mutex;

void create_clnt_socks(void)
{
    pthread_mutex_init(&g_mutex, NULL);
    return;
}

void destroy_clnt_socks(void)
{
    pthread_mutex_destroy(&g_mutex);
    return;
}

void add_clnt_sock(int clnt_sock)
{
    char name[NAME_SIZE];
    read(clnt_sock, name, NAME_SIZE);
    pthread_mutex_lock(&g_mutex);
    strcpy(g_cln_names[g_clnt_cnt], name);
    g_clnt_socks[g_clnt_cnt++] = clnt_sock;
    pthread_mutex_unlock(&g_mutex);
    return;
}

void del_clnt_sock(int clnt_sock)
{
    int i;
    for (i = 0; i < g_clnt_cnt; i++)
    {
        if (clnt_sock == g_clnt_socks[i])
        {
            while (i++ < g_clnt_cnt - 1)
            {
                g_clnt_socks[i] = g_clnt_socks[i + 1];
            }
            break;
        }
    }
    g_clnt_cnt--;
    return;
}

void send_msg_to_all(char *msg, int len)
{
    int i;
    for (i = 0; i < g_clnt_cnt; i++)
    {
        write(g_clnt_socks[i], msg, len);
    }
}

void one_to_one(char *name, char *msg, int sock_cln)
{
    int i, p;
    char name_msg[BUF_SIZE];
    for (p = 0; g_clnt_socks[p] != sock_cln; p++)
        ;
    for (i = 0; i < g_clnt_cnt; i++)
    {
        if (!strcmp(name, g_cln_names[i]))
        {
            sprintf(name_msg, "You receive a private message from %s : %s", g_cln_names[p], msg);
            write(g_clnt_socks[i], name_msg, BUF_SIZE);
        }
    }
}